package com.contact.util.util.search;

import java.util.Collection;


/**
 * Abstraction for processing large sets of data one page at a time
 * 
 * @param <T>
 */
public class PageProcessor<T> {

    protected int pageSize;
    protected ResultItemSort resultItemSort = null;

    public PageProcessor(int pageSize) {
        super();
        this.pageSize = pageSize;
    }
    
    public PageProcessor(int pageSize, ResultItemSort resultItemSort) {
        super();
        this.pageSize = pageSize;
        this.resultItemSort = resultItemSort;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public void processAll(DataProcessorSource<T> source, DataProcessor<T> dataProcessor) throws DataSourceException {

        PaginationInfo paginationInfo = PaginationInfo.createPaginationInfo();
        paginationInfo.setMaxResults(pageSize);
        if (resultItemSort != null) {
            paginationInfo.setResultItemSort(resultItemSort);
        }

        int i = 0;
        Collection<T> data;
        do {
            paginationInfo.setFirstRow(i);
            data = source.getData(paginationInfo);
            int dataSize = data.size(); //store data size in case the dataProcessor modifies it.
            dataProcessor.process(data);
            i += dataSize;
        } while (data.size() == pageSize);
    }
}
